package com.chenfeng.ego.sso.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chenfeng.ego.commons.pojo.EgoResult;
import com.chenfeng.ego.pojo.TbUser;
import com.chenfeng.ego.sso.service.UserService;
@Controller
public class UsrController
{
	@Resource
	private UserService userService;
	//登录页面
	@RequestMapping("user/showLogin")
	public String showLogin(@RequestHeader(name="Referer") String Referer,Model model,String oldpage)
	{
		if(!Referer.startsWith("http://localhost:8084"))
		{
		model.addAttribute("redirect", Referer);
		}
		if(oldpage!=null&&"".equals(oldpage))
		{
			model.addAttribute("redirect", oldpage);	
		}
			
		return "login";
	}
	//判断登录是否成功  成功的话本控制器调用的service会将cookie存放在起来返回客户端  并将uuid存放到redis中
	@RequestMapping("user/login")
	@ResponseBody
	public EgoResult login(TbUser user,HttpServletRequest req,HttpServletResponse res)
	{
		return userService.login(user,req,res);
	}
	//将redis里面存放的值取出来然后放进jsop所需的值穿进去 
	//需要返回responsebody calllback名字
	@RequestMapping("user/token/{token}")
	@ResponseBody
	public MappingJacksonValue token(@PathVariable String token,String callback,HttpServletRequest req,HttpServletResponse res)
	{
		MappingJacksonValue mjv = new MappingJacksonValue(userService.getTokenResult(token, req, res));
		mjv.setJsonpFunction(callback);
		return mjv;
	}
	//退出 退出的时候要销毁redis中存储的数据以及cookie里面存储的
	@RequestMapping("user/logout.html")
	public String lgout(String token ,HttpServletRequest req,HttpServletResponse res,@RequestHeader(name="Referer") String url)
	{
		this.userService.lgout(token, req, res);
		return "redirect:"+url;
	}
	//注册页面  注册成功之后会跳转到登录页面而登录页面  登录地址的参数将带有此次相应结果的rfferer参数就可以成功跳回到登录之前的页面
	@RequestMapping("user/showRegister")
	public String resigin(@RequestHeader(name="Referer")String referer,Model model)
	{   model.addAttribute("url",referer);        
		return "register";
	}
	//检测是否合法
	@RequestMapping("user/check/{countent}/{type}")
	@ResponseBody
	public EgoResult check(@PathVariable String countent,@PathVariable int type)
	{
		return userService.check(countent, type);
	}
	
	//开始注册
	@RequestMapping("/user/register")
	@ResponseBody
	public EgoResult register(TbUser user)
	{
		return userService.register(user);
	}
	
}
